#ifndef DIALOGMAIN_H
#define DIALOGMAIN_H

#include <QDialog>
#include <QTime>

#include "qextserialport.h"
#include "qextserialenumerator.h"

struct MiscInfo {
    int mLogIntervalMinute;
};

struct SerialPort {
    QString mName;
    PortSettings mPortSettings;
};

#define DEF_INI_FILENAME    "cubepower.ini"

#define PACKET_MIN_LEN      5
#define PACKET_SLAVE_ADDR   1

namespace Ui {
class DialogMain;
}

class DialogMain : public QDialog
{
    Q_OBJECT

public:
    explicit DialogMain(QWidget *parent = 0);
    ~DialogMain();

protected:
    virtual void timerEvent(QTimerEvent *e);

private:
    void loadConfig(const QString fileName);
    void saveConfig(const QString fileName);
    void initContextMenu();
    void initWidget();
    void initSerialPort();

    // MODBUS SERIAL
    // slave_address(1) + function_code(1) + data(0~252, big-endian) + crc(2, little-endian)
    // data(big-endian), crc(little-endian)
    // 30001 ~ 40000 : Read input registers
    // 40001 ~ 50000 : Read/Write holding registers
    unsigned short modbusCrc(unsigned char *data, int length);
    void modbusSetTime(QByteArray &ba);
    void modbusGetTime(QByteArray &ba);
    void modbusGetSum(QByteArray &ba);

    void savePowerLog(unsigned int sum1, unsigned int this_month1, unsigned int last_month1,
                      unsigned int sum2, unsigned int this_month2, unsigned int last_month2);

Q_SIGNALS:
    void signalNeedToShow();
    void signalDayChange(const QDateTime &dt);
    void signalMinuteChange(const QDateTime &dt);

public Q_SLOTS:
    void onParseArgs(const QString& args);
    //void onLog(const QString log);

private Q_SLOTS:
    void onShowContextMenu(const QPoint& pos);
    void onMenuSerialPort();
    void onMenuSetTime();
    void onMenuGetTime();
    void onMenuGetSum();
    void onMenuExit();
    void onDayChanged(const QDateTime &dt);
    void onMinuteChanged(const QDateTime &dt);

    void onSerialPortOpen();
    void onSerialPortClose();
    void onSerialPortSend();
    void onSerialPortRead();
    void onSerialPortAdded(QextPortInfo portInfo);
    void onSerialPortRemoved(QextPortInfo portInfo);

private:
    Ui::DialogMain *ui;

    int mOneSecondTimerId;

    MiscInfo mMiscInfo;
    SerialPort mSerialPort;

    QextSerialPort *mpSerialPort;
    QextSerialEnumerator *mpSerialEnumerator;

    QByteArray mSerialPortRecvBuf;
};

#endif // DIALOGMAIN_H
